<?php
require_once 'Artdepot/Controller/Action.php';

class ArtworkController extends Artdepot_Controller_Action
{

    public function init()
    {
		parent::init();
    }

    public function indexAction()
    {
    	$cateId = intval($this->_getParam('catId', 0));
		$categoryId = intval($this->_getParam('category', 0));
		$currency = strtoupper($this->_getParam('currency', 'USD'));
		$artist = intval($this->_getParam('artist', 0));
		$keyword = $this->_getParam('keyword', '');
		$page = intval($this->_getParam('page', 1));
    	if (!in_array($currency, array('EUR', 'USD', 'RMB'))) {
			$currency = 'USD';
		}
		if (strlen($keyword)>30) {
			$keyword = '';
		}
		
		if (empty($page)) {
			$page = 1;
		}
		
		$artworkTable = new Model_DbTable_ArtWork();
		$cateTable = new Model_DbTable_ArtworkCategory();
		$cates = $cateTable->fetchAll();
		$categories = array();
		$categoriesMap = array();
		$subIds = array();
		$subIds[] = $cateId;
		foreach ($cates as $cate) {
			if ($cate['parent']==0) {
				$categories[$cate['id']]['self'] = $cate; 
			} else {
				$categoriesMap[$cate['id']] = $cate->name;
				$categories[$cate['parent']]['childs'][] = $cate;
				if ($cateId && $cate['parent']==$cateId) {
					$subIds[] = $cate->id;
				}
			}
		}
		$subIds = implode(',', $subIds);
		$parentCategoryId = 0;
		$currentCategory = $cateTable->find($categoryId)->current();
		
		$where = '1';
		if ($categoryId) {
			$where .= " and category=$categoryId";
		}
		if ($cateId) {
			$where .= " and category in ({$subIds})";
		}
		
//		if ($artist) {
//			$where .= " and artist=$artist";
//		}
		
//		if ($keyword) {
//			
//			$escaped = $cateTable->getDefaultAdapter()
//								->quote("%$keyword%");
//								
//			$subjectTable = new Model_DbTable_Subject();
//			$styleTable = new Model_DbTable_Styles();
//			$searchStyles = $styleTable->fetchAll("name LIKE {$escaped}");
//			$searchsubjects = $subjectTable->fetchAll("name LIKE {$escaped}");
//			
//			
//			if ($artist) {
//				$where .= " and (name like {$escaped}";
//				if ($searchStyles->count() > 0) {
//					foreach ($searchStyles as $matchedStyles){
//						$where .= " OR FIND_IN_SET ($matchedStyles->id, `style`)";
//					}
//				}
//					
//				if ($searchsubjects->count() > 0) {
//					foreach ($searchsubjects as $matchedSubject){
//						$where .= " OR FIND_IN_SET ($matchedSubject->id, `subject`)";
//					}
//				}
//				$where .= ")";
//			}else{
//				/**
//				 * try to fetch artist by key words
//				 */
//				$artistTable = new Model_DbTable_Artist();
//				$searchArtists = $artistTable->fetchAll("name like $escaped");
//				if ($searchArtists->count() > 0) {
//					$theArtistIds = array();
//					foreach ($searchArtists as $matchedArtist){
//						$theArtistIds[] = $matchedArtist->id;
//					}
//					$artistCondition = join(",", $theArtistIds);
//				}
//				
//				if ($artistCondition){
//					$where .= " and (name like {$escaped} OR artist IN ({$artistCondition})";
//					
//					if ($searchStyles->count() > 0) {
//						foreach ($searchStyles as $matchedStyles){
//							$where .= " OR FIND_IN_SET ($matchedStyles->id, `style`)";
//						}
//					}
//						
//					if ($searchsubjects->count() > 0) {
//						foreach ($searchsubjects as $matchedSubject){
//							$where .= " OR FIND_IN_SET ($matchedSubject->id, `subject`)";
//						}
//					}
//					
//					$where .= ")";
//				}else{
//					$where .= " and (name like {$escaped}";
//					
//					if ($searchStyles->count() > 0) {
//						foreach ($searchStyles as $matchedStyles){
//							$where .= " OR FIND_IN_SET ($matchedStyles->id, `style`)";
//						}
//					}
//						
//					if ($searchsubjects->count() > 0) {
//						foreach ($searchsubjects as $matchedSubject){
//							$where .= " OR FIND_IN_SET ($matchedSubject->id, `subject`)";
//						}
//					}
//					
//					$where .= ")";
//				}
//				
//				
//			}
//			
//		}
		
    	
		
		$perPage = 10;
		$offset = ($page-1)*10;
		$db = Zend_Db_Table_Abstract::getDefaultAdapter();
		$this->logger->debug($where);
		$totalItemsNum = $db->fetchOne("select count(*) from art_work where {$where}");
		$totalPages = ceil($totalItemsNum/$perPage);
		$artworks = $artworkTable->fetchAll($where, 'id desc', $perPage, $offset);
		$artistsTable = new Model_DbTable_Artist();
		$artistsMap = $artistsTable->getMap();
		$this->view->artists = $artistsMap; //performance;
		$this->view->categoriesMap = $categoriesMap; //performance;
		
		
		
		
		$encodedKeyword = urlencode($keyword);
		$url = "/artwork?catId={$cateId}&category={$currentCategory->id}&currency={$currency}&artist={$artist}&keyword={$encodedKeyword}&page={page}";
		$this->view->pager = self::pager($page, $perPage, $totalItemsNum, $url, 'on', '');
		
		$this->view->title = 'Works of art - ';
		$this->view->catId = $cateId;
		$this->view->page = $page;
		$this->view->artworks = $artworks;
		$this->view->keyword = $keyword;
		$this->view->currency = $currency;
		$this->view->artist = $artist;
		$this->view->categories = $categories;
		$this->view->currentCategory = $currentCategory;
		$this->view->parentCategoryId = $parentCategoryId = $currentCategory->parent;
    }
    
	public function jingpinAction()
    {
    	$cateId = intval($this->_getParam('catId', 0));
		$categoryId = intval($this->_getParam('category', 0));
		$currency = strtoupper($this->_getParam('currency', 'USD'));
		$artist = intval($this->_getParam('artist', 0));
		$keyword = $this->_getParam('keyword', '');
		$page = intval($this->_getParam('page', 1));
    	if (!in_array($currency, array('EUR', 'USD', 'RMB'))) {
			$currency = 'USD';
		}
		if (strlen($keyword)>30) {
			$keyword = '';
		}
		
		if (empty($page)) {
			$page = 1;
		}
		
		$artworkTable = new Model_DbTable_ArtWork();
		$cateTable = new Model_DbTable_ArtworkCategory();
		$cates = $cateTable->fetchAll();
		$categories = array();
		$categoriesMap = array();
		$subIds = array();
		$subIds[] = $cateId;
		foreach ($cates as $cate) {
			if ($cate['parent']==0) {
				$categories[$cate['id']]['self'] = $cate; 
			} else {
				$categoriesMap[$cate['id']] = $cate->name;
				$categories[$cate['parent']]['childs'][] = $cate;
				if ($cateId && $cate['parent']==$cateId) {
					$subIds[] = $cate->id;
				}
			}
		}
		$subIds = implode(',', $subIds);
		$parentCategoryId = 0;
		$currentCategory = $cateTable->find($categoryId)->current();
		
		$where = '1';
		if ($categoryId) {
			$where .= " and category=$categoryId";
		}
		if ($cateId) {
			$where .= " and category in ({$subIds})";
		}
		

		
    	
		
		$perPage = 10;
		$offset = ($page-1)*10;
		$db = Zend_Db_Table_Abstract::getDefaultAdapter();
		$this->logger->debug($where);
		$totalItemsNum = $db->fetchOne("select count(*) from art_work where typical = 'Y' AND {$where}");
		$totalPages = ceil($totalItemsNum/$perPage);
		$artworks = $artworkTable->fetchAll( "typical = 'Y' AND ". $where, 'id desc', $perPage, $offset);
		$artistsTable = new Model_DbTable_Artist();
		$artistsMap = $artistsTable->getMap();
		$this->view->artists = $artistsMap; //performance;
		$this->view->categoriesMap = $categoriesMap; //performance;
		
		
		
		
		$encodedKeyword = urlencode($keyword);
		$url = "/artwork/jingpin?catId={$cateId}&category={$currentCategory->id}&currency={$currency}&artist={$artist}&keyword={$encodedKeyword}&page={page}";
		$this->view->pager = self::pager($page, $perPage, $totalItemsNum, $url, 'on', '');
		
		$this->view->title = '现货精品 - ';
		$this->view->catId = $cateId;
		$this->view->page = $page;
		$this->view->artworks = $artworks;
		$this->view->keyword = $keyword;
		$this->view->currency = $currency;
		$this->view->artist = $artist;
		$this->view->categories = $categories;
		$this->view->currentCategory = $currentCategory;
		$this->view->parentCategoryId = $parentCategoryId = $currentCategory->parent;
    }

    public function showAction()
    {
		$id = $this->_getParam('id', 0);
		$artworkTable = new Model_DbTable_ArtWork();
		$artistTable = new Model_DbTable_Artist();
		$cateTable = new Model_DbTable_ArtworkCategory();
		$subjectTable = new Model_DbTable_Subject();
		$styleTable = new Model_DbTable_Styles();
		$artwork = $artworkTable->find($id)->current();
		if (!$artwork instanceof Model_Artwork) {
			$this->error('Artwork not found.');
			return;
		}
		
		
		$artist = $artistTable->find($artwork->artist)->current();
		$comparableWorks = array();
		$comparableWorks = $artworkTable->fetchAll("artist = $artwork->artist", 'RAND() desc', 4);
		$category = $cateTable->find($artwork->category)->current();
		$parentCategory = $cateTable->find($category->parent)->current();
		$this->view->title = $artwork->name . ' - ';
		$this->view->subjectMap = $subjectTable->getMap();
		$this->view->styleMap = $subjectTable->getMap();
		$this->view->category = $category;
		$this->view->parentCategory = $parentCategory;
		$this->view->artwork = $artwork;
		$this->view->artist = $artist;
		$this->view->comparableWorks = $comparableWorks;
		
		
		
		
		
    }
    
	public function addOrderAction(){
    	$this->view->title = 'Create Order - ';
    	$artworkId = (int) $this->_request->getParam("artworkId");
    	if($artworkId < 0){
    		$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    	}
    	
    	$table = new Model_DbTable_ArtWork();
    	$theArtWork = $table->fetchRow("id = $artworkId");
    	if (!$theArtWork){
    		$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    	}
    	if ($this->_request->isPost()){
    		$params = $this->_request->getParams();
    		
    		$salesEmail = $this->config["sales_email"];
    		$this->logger->debug($salesEmail);
    		$siteURL = $this->config["site_domain"];
	    	$emailTitle = "Order from " . $params['first_name']. " " .$params["last_name"];
	    	$emailContent = <<<EOF
	    	来自{$params['first_name']} {$params["last_name"]}的订单：<br/>
	    	
	    	作品名称：<a href="{$siteURL}/artwork/show/id/{$artworkId}" target="_blank">{$params['item_name']}</a><br />
	    	货号：{$params['item_number']}<br />
	    	数量：{$params['quantity']}<br />
	    	订购人电话：{$params['telphone']}<br />
	    	地址：{$params['address1']}<br />
	    	城市：{$params['city']}<br />
	    	州：{$params['state']}<br />
	    	国家：{$params['country']}<br />
	    	邮编：{$params['zip']}<br />
	    	附加信息：{$params['message']}<br />
	    	
EOF;

			$mail = new Zend_Mail();
			$mail->setBodyHtml($emailContent)
				->setSubject($emailTitle)
				->setFrom($params["email"], $params['first_name']." ".$params["last_name"])
				->addTo($salesEmail)
				->send();
				
			$this->view->message = "感谢您的订购，我们会尽快和您取得联系！";
    	}
    	
    	$this->view->artwork = $theArtWork;
    	
    }
    
	

    public function categoryAction()
    {
        // action body
    }
    
	public function deleteCommentAction(){
    	$id = (int) $this->_request->getParam("id");
    	$table = new Model_DbTable_ArtworkComment();
    	$theComment = $table->fetchRow("id = $id");
    	if ($theComment && ( $theComment->customer == $this->auth->getIdentity()->id || $this->admin->getIdentity() ) ){
    		$theComment->delete();
    	}
    	
    	$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    }
    
    public function addCommentAction(){
    	if ($this->_request->isPost() && $this->auth->getIdentity()) {
    		$form = new Form_ArtworkComment();
    		if ($form->isValid($this->_request->getPost())){
    			$table = new Model_DbTable_ArtworkComment();
    			$values = array();
    			$values["time"] = date("Y-m-d H:i:s");
    			$values["id"] = 0;
    			$values["artwork"] = $form->getValue("artwork");
    			$values["content"] = $form->getValue("content");
    			$values["customer"] = $this->auth->getIdentity()->id;
    			$table->insert($values);
    		}
    	}
    	
    	$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    }
    

}





